package com.example.shop.order.service.impl;

import com.example.shop.common.util.FileOptionUtil;
import com.example.shop.common.util.GenerateCodeUtil;
import com.example.shop.common.util.HttpURLConnectionHelper;
import com.example.shop.order.config.pay.WXNativePayConfig;
import com.example.shop.order.dto.WXNativePayOrder;
import com.example.shop.order.dto.WXPayQueryResult;
import com.example.shop.order.enums.PayStates;
import com.example.shop.order.service.WXNativePayService;
import com.example.shop.pojo.Order;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxpay.sdk.WXPay;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class WXNativePayServiceImpl implements WXNativePayService {

    private final WXPay wxPay;

    public WXNativePayServiceImpl(WXPay wxPay) {
        this.wxPay = wxPay;
    }

    @Override
    public String createNativePayUrl(WXNativePayOrder order) throws Exception {
        Map<String, String> reqData = new HashMap<>();
        reqData.put("body",order.getDescription());
        //订单号与该支付凭证绑定
        reqData.put("out_trade_no", String.valueOf(order.getOrder().getOrderId()));
        //过期时间
        reqData.put("time_expire", order.getOrderExpirationTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        reqData.put("fee_type", "CNY");
        reqData.put("total_fee", String.valueOf(order.getOrder().getRealPay()));
        reqData.put("notify_url", order.getNotifyUrl());
        reqData.put("trade_type","NATIVE");
        reqData.put("product_id", String.valueOf(order.getOrder().getGoodsId()));
        try {
            Map<String, String> resp = wxPay.unifiedOrder(reqData);
            if("SUCCESS".equals(resp.get("result_code"))){
                return resp.get("code_url");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new Exception("支付请求异常");
    }

    @Override
    public WXPayQueryResult queryOrder(long orderId) throws Exception {
        Map<String, String> reqData = new HashMap<>();
        reqData.put("out_trade_no", String.valueOf(orderId));
        Map<String, String> resp = wxPay.orderQuery(reqData);
        if(resp.get("return_msg").equals("OK")){
            WXPayQueryResult result = new WXPayQueryResult();
            result.setPayStates(PayStates.valueOf(resp.get("trade_state")))
                    .setOutTradeNo(Long.parseLong(resp.get("out_trade_no")));
            //如果查询到的订单支付成功，则设置该订单
            if(PayStates.SUCCESS.equals(result.getPayStates())){
                result.setTradeType(resp.get("trade_type"))
                        .setTransactionId(resp.get("transaction_id"));
            }
            return result;
        }
        throw new Exception("查询支付订单出错");
    }


}
